using B.S.NewMedical.Api.Write.Application.Command.Order.Consultation;
using B.S.NewMedical.Domain.Order;
using B.S.NewMedical.ErrorCode;
using B.S.NewMedical.Infrastructure.Interface;
using MediatR;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.NewMedical.Api.Write.Application.Handler.Order.Consultation
{
    /// <summary>
    /// 批量删除问诊记录处理器
    /// </summary>
    public class BatchDeleteConsultationCommandHandle : IRequestHandler<BatchDeleteConsultationCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<ConsultationModel> _consultationRepository;
        private readonly ILogger<BatchDeleteConsultationCommandHandle> _logger;

        public BatchDeleteConsultationCommandHandle(
            IBaseRepository<ConsultationModel> consultationRepository,
            ILogger<BatchDeleteConsultationCommandHandle> logger)
        {
            _consultationRepository = consultationRepository;
            _logger = logger;
        }

        public async Task<ApiResult<int>> Handle(BatchDeleteConsultationCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<int>();

            try
            {
                _logger.LogInformation("开始批量删除问诊记录，数量：{Count}，操作人：{Operator}",
                    request.ConsultationIds.Count, request.Operator);

                // 1. 查找要删除的问诊记录
                var consultations = _consultationRepository.GetAll()
                    .Where(x => request.ConsultationIds.Contains(x.Id) && !x.IsDeleted)
                    .ToList();

                if (consultations == null || consultations.Count == 0)
                {
                    result.Code = ApiEnum.Fail;
                    result.Msg = "未找到要删除的问诊记录";
                    _logger.LogWarning("未找到要删除的问诊记录，IDs：{Ids}",
                        string.Join(",", request.ConsultationIds));
                    return result;
                }

                // 2. 检查是否有已完成的问诊记录
                var completedConsultations = consultations
                    .Where(x => !string.IsNullOrEmpty(x.Orderstatus) &&
                               x.Orderstatus.Equals("已完成", StringComparison.OrdinalIgnoreCase))
                    .ToList();

                if (completedConsultations.Any())
                {
                    var completedIds = string.Join(",", completedConsultations.Select(x => x.Id));
                    result.Code = ApiEnum.Fail;
                    result.Msg = $"以下问诊记录已完成，不能删除：{completedIds}";
                    _logger.LogWarning("尝试删除已完成的问诊记录，IDs：{Ids}", completedIds);
                    return result;
                }

                // 3. 执行批量逻辑删除
                var currentTime = DateTime.Now;
                foreach (var consultation in consultations)
                {
                    consultation.IsDeleted = true;
                    consultation.UpdateTime = currentTime;
                    consultation.UpdatePeople = request.Operator;
                }

                // 4. 记录删除原因
                if (!string.IsNullOrEmpty(request.DeleteReason))
                {
                    _logger.LogInformation("批量删除问诊记录原因：{DeleteReason}，IDs：{Ids}",
                        request.DeleteReason, string.Join(",", request.ConsultationIds));
                }

                // 5. 批量更新数据库
                var updateResult = await _consultationRepository.UpdateRangAsync(consultations);

                if (updateResult > 0)
                {
                    result.Code = ApiEnum.Success;
                    result.Msg = $"成功删除 {updateResult} 条问诊记录";
                    result.Data = updateResult;

                    _logger.LogInformation("批量删除问诊记录成功，数量：{Count}，IDs：{Ids}，操作人：{Operator}",
                        updateResult, string.Join(",", request.ConsultationIds), request.Operator);
                }
                else
                {
                    result.Code = ApiEnum.Fail;
                    result.Msg = "批量删除问诊记录失败";
                    result.Data = updateResult;

                    _logger.LogError("批量删除问诊记录失败，IDs：{Ids}，操作人：{Operator}",
                        string.Join(",", request.ConsultationIds), request.Operator);
                }
            }
            catch (Exception ex)
            {
                result.Code = ApiEnum.Error;
                result.Msg = $"批量删除问诊记录时发生异常：{ex.Message}";

                _logger.LogError(ex, "批量删除问诊记录时发生异常，IDs：{Ids}，操作人：{Operator}，异常信息：{Message}",
                    string.Join(",", request.ConsultationIds), request.Operator, ex.Message);
            }

            return result;
        }
    }
}